package com.kb.erp.service.impl.crm;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kb.erp.domain.crm.PublicPool;
import com.kb.erp.entity.crm.Customer;
import com.kb.erp.mapper.sqlServer.crm.CRMCustomerMapper;
import com.kb.erp.mapper.sqlServer.crm.CRMSalesOrderMapper;
import com.kb.erp.mapper.sqlServer.crm.CRMUserInfoMapper;
import com.kb.erp.mapper.sqlServer.crm.CustomerAddressMapper;
import com.kb.erp.service.HrService;
import com.kb.erp.service.crm.CrmLowCodeService;
import com.kb.erp.util.MessageUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import java.util.List;

@Service
@DS("SmartQuote_kb_live")
public class CrmLowCodeServiceImpl implements CrmLowCodeService {

    @Resource
    private CRMSalesOrderMapper crmSalesOrderMapper;
    @Resource
    private CRMCustomerMapper customerMapper;
    @Resource
    private CRMUserInfoMapper crmUserInfoMapper;
    @Resource
    private CustomerAddressMapper customerAddressMapper;
    @Resource
    private HrService hrService;


    @Override
    public void transferToPublicPool(PublicPool publicPool) {
        List<Customer> excel = publicPool.getExcel();
        for (Customer customer1 : excel) {
            try {
                LambdaQueryWrapper<Customer> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(Customer::getCustcode, customer1.getCustcode());
//            queryWrapper.last("limit 1");
                Customer one = customerMapper.selectOne(queryWrapper);
                one.setDepartmentid(publicPool.getPublicPoolId());
                one.setSysuserid(publicPool.getSalesman());
                //更新用户表
                int update = customerMapper.updateById(one);
                if (update > 0){
                    System.out.println("更新成功: "+customer1.getCustcode());
                }
                //更新客户销售人关系表 CompanyUserRelation
                customerMapper.updateCompanyUserRelation(publicPool.getSalesman(),one.getRecid());
            } catch (Exception e) {
                System.out.println("更新失败: "+customer1.getCustcode());
                MessageUtil.sentMessage("23988",customer1.getCustcode(), "转移客户数据到公海失败");
            }
        }

    }

    @Override
    public void batchSubmit(String ids) {
        //ids 根据 ,号分割
        try {
            String[] split = ids.split(",");
            for (String id : split) {
                customerMapper.batchSubmit(id);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
